var http = require('http');
var qs = require('querystring');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/mymusix');


var urltoid = function(url){
    var type = 'V';
    var match = url.match('vimeo.com/([0-9]+)');
    if ( ! match)
    {
        type = 'Y';
        match = url.match('youtube.com/watch\\?v=([a-zA-Z0-9_\-]+)(&.*){0,1}');
    }

    if ( ! match)
    {
        type = null;
        return null;
    }
    var id = type + '.' + match[1];
    return id;
};

var userhasmusic = function(musicid, userid, callback){
    var collection = db.get('usermusic');
    collection.find({
        _id: userid.toString(),
        music: musicid
    },{},function(e, docs){
        if (docs && docs.length > 0)
        {
            callback({success:true});
        }else
        {
            callback({success:false});
        }
    });
};

var musicexists = function(musicid, callback){
    var collection = db.get('music');
    collection.find({
        _id: musicid.toString()
    },{},function(e, docs){
        if (docs && docs.length > 0)
        {
            callback({success:true});
        }else
        {
            callback({success:false});
        }
    });
};

exports.add = function(data, listener) {
    if (typeof data.url !== 'undefined')
    {
        var musicid = urltoid(data.url);
        if (musicid === null)
        {
            listener({success: false});
            return;
        }
        musicexists(musicid, function(r){
            if (r.success)
            {
                if (typeof data.userid !== 'undefined')
                {
                    exports.useradd(data, function(){});
                }
                listener({success: true});
            }
            else
            {
                var options = {
                    host: 'localhost',
                    port: 8080,
                    path: '/FileService/link/save?data='+JSON.stringify({url:data.url}),
                    method: 'GET'
                };

                http.request(options, function(res) {
                    res.setEncoding('utf8');
                    var buffer = '';
                    res.on('data', function(chunk) {
                        buffer += chunk;
                    });
                    res.on("end", function() {
                        var response = JSON.parse(buffer);
                        if (response.success && typeof data.userid !== 'undefined')
                        {
                            exports.useradd(data, function(){});
                        }
                        listener({success: response.success, messages: response.messages});
                    });
                }).end();
            }
        });
    }
    else if(
            typeof data.type !== 'undefined' && 
            typeof data.code !== 'undefined' && 
            typeof data.title !== 'undefined' &&
            data.type !== null && 
            data.code !== null && 
            data.title !== null &&
            data.type.trim() !== '' &&
            data.code.trim() !== '' &&
            data.title.trim() !== '')
    {
        var value = {
            '_id': data.type.trim() + '.' + data.code.trim(),
            'title': data.title.trim()
        };
        var collection = db.get('music');
        collection.insert(value, function (err, doc) {
            listener({success:!(err), data: value});
        });
    }else
    {
        console.log('hier darf man nicht sein');
        listener({
            success: false,
            data: null,
            message: 'kein zu verarbeitender datensatz gefunden'
        });
    }
    
};

exports.listall = function(data, listener) {
    var collection = db.get('music');
    collection.find({}, {}, function(e, docs) {
        listener({docs: docs});
    });
};

exports.useradd = function(data, listener){
    if (typeof data.url !== 'undefined' && typeof data.userid !== 'undefined')
    {
        var musicid = urltoid(data.url);
        if (musicid === null)
        {
            listener({success: false});
            return;
        }

        var collection = db.get('usermusic');
        collection.update({
            _id: data.userid
        },{
            $addToSet: { music: musicid  },
            $set: { last: musicid  }
        },{
            upsert: true,
            multi: false
        });
        listener({success:true});
        return;
    }
    listener({success:false});
};

exports.check = function(data, listener){
    if (typeof data.url !== 'undefined' && typeof data.userid !== 'undefined')
    {
        var musicid = urltoid(data.url);
        if (musicid === null)
        {
            listener({success: false});
            return;
        }
        
        userhasmusic(musicid, data.userid, function(r){
            if (r.success)
            {
                musicexists(musicid, function(r2){
                    if (r2.success)
                    {
                        listener({success:true, data:{state:2}});
                    }
                    else
                    {
                        listener({success:true, data:{state:1}});
                    }
                });
            }else
            {
                listener({success:true, data:{state:0}});
            }
        });
        return;
    }
    listener({success:false});
};

exports.userlist = function(data, listener){
    var collection = db.get('usermusic');
    collection.find({'_id':data.userid.toString()}, {}, function(e, docs) {
        if (docs && docs.length === 1)
        {
            var um = docs[0];
            db.get('music').find({_id:{$in:um.music}},{}, function(e, dox){
                if (dox)
                {
                    var last = 'none';
                    if (typeof um.last !== 'undefined')
                    {
                        last = um.last;
                    }
                    listener({success:true, data: dox, last: last});
                }else
                {
                    listener({success:true, data: [], last: null});
                }
            });
            
        }
        else
        {
            listener({success:true, data: []});
        }
    });
};

exports.userlast = function(data, listener){
    if (typeof data.last === 'undefined' || data.last === null)
    {
        listener({success:false, data: null, message: 'invalid request'});
    }
    var collection = db.get('usermusic');
    collection.find({'_id':data.userid.toString()}, {}, function(e, docs) {
        if (docs && docs.length === 1)
        {
            var um = docs[0];
            var last = 'none';
            if (typeof um.last !== 'undefined')
            {
                last = um.last;
            }
            var out = {
                requested: data.last,
                last: last,
                changed: data.last !== last
            };
            listener({success:true, data: out});
        }
        else
        {
            listener({success:true, data: null});
        }
    });
};